<template>
  <!--  查询框区-->
  <div class="search">
    <el-form inline :model="adminSearchModel" ref="adminSearchForm">
      <el-form-item label="管理员姓名: ">
        <el-input v-model="adminSearchModel.name" placeholder="请输入管理员姓名" clearable/>
      </el-form-item>
      <el-form-item label="手机号: ">
        <el-input v-model="adminSearchModel.phone" placeholder="请输入手机号" clearable/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="search()">查询</el-button>
        <el-button :icon="Refresh" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </div>

  <!--  按钮区 -->
  <div class="action">
    <div class="action-left">
      <el-button type="primary" :icon="CirclePlus" @click="add">新增</el-button>
      <el-button :icon="Edit" @click="edit">修改</el-button>
      <el-button type="danger" :icon="Delete" @click="remove()">删除</el-button>
    </div>
    <div class="action-right">
      <span class="total-count">共 {{ adminsPi.total }} 条记录</span>
    </div>
  </div>

  <!--  表格区-->
  <div class="grid">
    <el-table :data="admins"
              stripe
              border
              @row-click="tblRowClick"
              ref="tblRef"
              style="width: 100%"
              v-loading="tableLoading">
      <el-table-column type="selection" align="center" width="60"/>
      <el-table-column prop="id" label="编号" align="center" width="100"/>
      <el-table-column prop="name" label="姓名" align="center" min-width="150"/>
      <el-table-column prop="phone" label="手机号" min-width="180"/>
      <el-table-column label="操作" min-width="200" align="center" fixed="right">
        <template #default="scope">
          <el-button type="primary" size="small" @click.stop="editRow(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click.stop="deleteRow(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <!--  添加、修改弹出表单-->
  <el-dialog :title="adminDlgTitle" v-model="adminDlgShow" align-center :close-on-click-modal="false"
             @close="resetAdminForm" width="500px">
    <el-form
        label-width="100"
        label-position="right"
        :model="adminModel"
        ref="adminFormRef"
        :rules="adminRules">
      <el-form-item prop="name" label="姓名：">
        <el-input v-model="adminModel.name" placeholder="请输入管理员姓名"/>
      </el-form-item>
      <el-form-item prop="phone" label="手机号：">
        <el-input v-model="adminModel.phone" placeholder="请输入管理员手机号"/>
      </el-form-item>
      <el-form-item prop="password" label="密码：" v-if="mode === 'add'">
        <el-input v-model="adminModel.password" placeholder="请输入密码" type="password"/>
      </el-form-item>
      <el-form-item prop="password" label="新密码：" v-else>
        <el-input v-model="adminModel.password" placeholder="留空则不修改密码" type="password"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div>
        <el-button @click="adminDlgShow=false">取消</el-button>
        <el-button type="primary" @click="submit" :loading="dialogLoading">确定</el-button>
      </div>
    </template>
  </el-dialog>

  <!--  分页区-->
  <div class="pagination">
    <el-pagination
        v-model:current-page="adminsPi.pageNo"
        v-model:page-size="adminsPi.pageSize"
        layout="prev, pager, next, jumper, ->, total"
        :total="adminsPi.total"
        @current-change="adminPiChange"
        background
    />
  </div>
</template>

<script setup>
import {onMounted, reactive, ref, toRaw, nextTick} from "vue"
import api from "@/utils/api.js";
import {CirclePlus, Delete, Edit, Refresh, Search} from "@element-plus/icons-vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {cloneDeep} from "lodash";

// 表格数据
let admins = ref([])
let tableLoading = ref(false)
let dialogLoading = ref(false)

// 查询表单引用
let adminSearchForm = ref()
// 表格引用
let tblRef = ref()

// 分页
let adminsPi = reactive({
  pageNo: 1,
  pageSize: 7,
  total: 0
})

// 查询条件
let adminSearchModel = ref({
  name: "",
  phone: ""
})

// 表单验证规则
const adminRules = {
  name: [
    { required: true, message: '请输入管理员姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度应在 2 到 20 个字符之间', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应在 6 到 20 个字符之间', trigger: 'blur' },
    { pattern: /^(?=.*[a-zA-Z])(?=.*\d).+$/, message: '密码必须包含字母和数字', trigger: 'blur' }
  ]
}

// 查询管理员
async function search(pageNo = 1, pageSize = 7, params) {
  tableLoading.value = true
  params = adminSearchModel.value
  try {
    let resp = await api({
      url: "/admin",
      method: "get",
      params: {
        pageNo,
        pageSize,
        ...params
      }
    });

    if (resp && resp.success) {
      admins.value = resp.data.records
      adminsPi.total = resp.data.total
      adminsPi.pageNo = resp.data.current
      adminsPi.pageSize = resp.data.size
    }
  } catch (error) {
    ElMessage.error("查询失败: " + (error.message || "网络错误"))
  } finally {
    tableLoading.value = false
  }
}

// 重置查询条件
function reset() {
  adminSearchModel.value = {
    name: "",
    phone: ""
  }
  search()
}

// 表格行点击
function tblRowClick(row) {
  tblRef.value.toggleRowSelection(row)
}

// 删除管理员
async function deleteAdminById(ids) {
  try {
    let resp = await api({
      url: "/admin",
      method: "delete",
      data: ids
    })

    if (resp && resp.success) {
      ElMessage.success("删除成功")
      search(adminsPi.pageNo, adminsPi.pageSize);
    } else {
      ElMessage.error("删除失败: " + (resp.message || "未知错误"))
    }
  } catch (error) {
    ElMessage.error("删除失败: " + (error.message || "网络错误"))
  }
}

function remove() {
  let rows = tblRef.value.getSelectionRows();
  if (rows.length === 0) {
    ElMessage.warning("请选择要删除的行")
  } else {
    ElMessageBox.confirm(`确定要删除选中的 ${rows.length} 个管理员吗？`, "删除确认", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }).then(() => {
      let ids = rows.map(item => item.id);
      deleteAdminById(ids);
    }).catch(() => {
      ElMessage.info("已取消删除")
    })
  }
}

// 弹窗相关
let adminDlgTitle = ref("新增管理员")
let adminDlgShow = ref(false)
let mode = "add"

// 管理员表单数据
let adminModel = ref({
  id: null,
  name: null,
  phone: null,
  password: null
})

let adminFormRef = ref();

function add() {
  mode = "add"
  adminDlgTitle.value = "新增管理员"
  adminDlgShow.value = true
  // 重置表单
  nextTick(() => {
    adminModel.value = {
      id: null,
      name: null,
      phone: null,
      password: null
    }
  })
}

function edit() {
  let rows = tblRef.value.getSelectionRows();
  if (rows.length === 0) {
    ElMessage.warning("请选择要修改的行")
  } else if (rows.length > 1) {
    ElMessage.warning("只能选择一行")
  } else {
    mode = "edit"
    adminDlgTitle.value = "修改管理员"
    adminDlgShow.value = true
    nextTick(() => {
      let row = rows[0]
      adminModel.value = {
        id: row.id,
        name: row.name,
        phone: row.phone,
        password: null // 编辑时密码字段留空
      }
    })
  }
}

function editRow(row) {
  mode = "edit"
  adminDlgTitle.value = "修改管理员"
  adminDlgShow.value = true
  nextTick(() => {
    adminModel.value = {
      id: row.id,
      name: row.name,
      phone: row.phone,
      password: null // 编辑时密码字段留空
    }
  })
}

function resetAdminForm() {
  if (adminFormRef.value) {
    adminFormRef.value.resetFields()
  }
}

async function submit() {
  // 表单验证
  try {
    await adminFormRef.value.validate()
  } catch (error) {
    ElMessage.warning("请检查输入信息")
    return
  }

  dialogLoading.value = true

  // 构造提交数据
  let params = toRaw(adminModel.value)

  // 如果是编辑模式且密码为空，则不提交密码字段
  if (mode === 'edit' && !params.password) {
    delete params.password
  }

  let url, method
  if (mode === 'add') {
    url = "/admin"
    method = "post"
  } else if(mode === 'edit') {
    url = "/admin"
    method = "put"
  }

  try {
    let resp = await api({
      url,
      method,
      data: params
    })
    if (resp && resp.success) {
      ElMessage.success(mode === 'add' ? '添加成功' : '修改成功')
      adminDlgShow.value = false
      await search(adminsPi.pageNo, adminsPi.pageSize)
    } else {
      ElMessage.error(resp?.message || '操作失败')
    }
  } catch (error) {
    ElMessage.error('请求失败: ' + (error.message || "网络错误"))
  } finally {
    dialogLoading.value = false
  }
}

function deleteRow(row) {
  ElMessageBox.confirm(`确定要删除管理员 ${row.name} 吗？`, "删除确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteAdminById([row.id])
  }).catch(() => {
    ElMessage.info("已取消删除")
  })
}

// 分页改变
function adminPiChange(pageNo) {
  search(pageNo, adminsPi.pageSize)
}

onMounted(() => {
  search(1, adminsPi.pageSize)
})
</script>

<style scoped>
.search {
  padding: 20px;
  background: white;
  border-radius: 10px;
  margin-bottom: 20px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.search .el-form {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.search .el-form-item {
  margin-bottom: 0;
}

.search .el-form-item__label {
  font-weight: 500;
}

.action {
  padding: 15px 20px;
  background: white;
  border-radius: 10px;
  margin-bottom: 20px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.action-left {
  display: flex;
  gap: 12px;
}

.action-right {
  font-size: 14px;
  color: #666;
}

.total-count {
  font-weight: 500;
}

.grid {
  background: white;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.el-table {
  margin-top: 10px;
}

.el-table :deep(.el-table__cell) {
  padding: 12px 8px;
}

.el-table :deep(th.el-table__cell) {
  background-color: #f8f9fa;
  color: #333;
  font-weight: 500;
  font-size: 14px;
}

/* 表格行悬停效果 */
.el-table :deep(.el-table__row:hover) {
  background-color: #f5f7ff;
}

.el-dialog {
  border-radius: 12px;
}

.el-dialog :deep(.el-dialog__header) {
  border-bottom: 1px solid #eee;
  margin-right: 0;
}

.el-dialog :deep(.el-dialog__body) {
  padding: 25px;
}

.el-dialog :deep(.el-dialog__footer) {
  border-top: 1px solid #eee;
  padding: 15px 25px;
}

.el-form-item {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  padding: 15px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.el-button {
  border-radius: 8px;
  transition: all 0.2s ease;
  font-weight: 500;
}

.el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.el-button--primary {
  background-color: #1e3c72;
  border-color: #1e3c72;
}

.el-button--primary:hover {
  background-color: #2a5298;
  border-color: #2a5298;
}

.el-button--danger {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

.el-button--danger:hover {
  background-color: #f78989;
  border-color: #f78989;
}


.el-input__inner,
.el-textarea__inner {
  border-radius: 8px;
  border: 1px solid #ddd;
  transition: border-color 0.2s;
}

.el-input__inner:focus,
.el-textarea__inner:focus {
  border-color: #2a5298;
  box-shadow: 0 0 0 2px rgba(0, 122, 255, 0.2);
}

/* 分页样式优化 */
:deep(.el-pagination .el-pager li) {
  border-radius: 6px;
}

:deep(.el-pagination .btn-prev),
:deep(.el-pagination .btn-next) {
  border-radius: 6px;
}

:deep(.el-pagination .el-pagination__jump) {
  margin-left: 16px;
}
</style>
